import {
  Module,
  NestModule,
  MiddlewareConsumer,
  RequestMethod,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserController } from './controller/user/user.controller';
import { NewsController } from './controller/news/news.controller';
import { ProductController } from './controller/product/product.controller';
import { InitMiddleware } from './middleware/init/init.middleware';
import { UserMiddleware } from './middleware/user/user.middleware';
import { NewsMiddleware } from './middleware/news/news.middleware';

// 函数式中间件
function logger(req, res, next) {
  console.log('Request...');
  next();
}

@Module({
  imports: [],
  controllers: [
    AppController,
    UserController,
    NewsController,
    ProductController,
  ],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // 单个中间件的使用
    // consumer
    //   // 具体的匹配方法可以查看官方文档，还有很多种
    //   .apply(InitMiddleware)
    //   // .forRoutes('*'); // * 代表匹配所有的路由
    //   // .forRoutes('news'); // 匹配指定路由
    //   .forRoutes(
    //     { path: 'user', method: RequestMethod.ALL },
    //     { path: 'news', method: RequestMethod.ALL },
    //   ); // 匹配多个路由

    //   // 多个中间件的使用
    //   consumer
    //     .apply(InitMiddleware)
    //     .forRoutes('*')
    //     .apply(UserMiddleware)
    //     .forRoutes({ path: 'user', method: RequestMethod.ALL });

    // 匹配多个中间件，以及匹配多个路由
    consumer
      .apply(UserMiddleware, NewsMiddleware, logger)
      .forRoutes(
        { path: 'user', method: RequestMethod.ALL },
        { path: 'news', method: RequestMethod.ALL },
      );
  }
}
